package com.aierjun.lgmusic.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aierjun.lgmusic.R;
import com.aierjun.lgmusic.fragment.MainFragmentActivity;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2016/10/10.
 */
public class LoginActivity extends Activity {
    private Handler handler;
    private OkHttpClient client=new OkHttpClient();
    String userName_ed;
    String passWord_ed;
    public static String token;
    int status;
    public static String username;
    public static String password;

    private EditText userName;
    private EditText passWd;
    private Button login;
    private TextView fixPassWd;
    private TextView NewUser;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        findView();
        initView();
        getToken();
        oneselfLogin();
    }

    private void findView() {
        userName= (EditText) findViewById(R.id.et_user_name);
        passWd= (EditText) findViewById(R.id.et_pass_word);
        login= (Button) findViewById(R.id.bt_login);
        fixPassWd= (TextView) findViewById(R.id.tv_forget_pwd);
        NewUser= (TextView) findViewById(R.id.tv_register);
    }

    private void initView() {
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            getExecute();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        fixPassWd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,ForgetPasswordActivity.class));
            }
        });
        NewUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
            }
        });

        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what==1){
                    startActivity(new Intent(LoginActivity.this, MainFragmentActivity.class));
                }else if (msg.what==2){
                    Toast.makeText(LoginActivity.this,msg.obj+"",Toast.LENGTH_SHORT).show();
                }
            }
        };
    }

    private void getExecute() throws IOException {
        userName_ed=userName.getText().toString();
        passWord_ed=passWd.getText().toString();
        Request request=new Request.Builder()
                .url("http://192.168.1.245:8080/music/musicianmanager/loginPerson?loginname="+userName_ed+"&loginpass="+passWord_ed)
                .build();
        Response response=client.newCall(request).execute();
        InputStream in=response.body().byteStream();
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        byte[] buf=new byte[1024];
        int len;
        if (response.isSuccessful()){
            while ((len=in.read(buf))!=-1){
                out.write(buf,0,len);
            }
            Log.d("JunLog",out+"");
            newsJsonStr(new String(out.toByteArray()));
            in.close();
            out.close();
        }else{
            Toast.makeText(LoginActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
        }
    }
    private void newsJsonStr(String objStr){
        try {
            JSONObject jsonObject=new JSONObject(objStr);
            if (jsonObject.getInt("code")==200){
                Log.d("JunLog","登录成功");
                token=jsonObject.getString("object");
                status=jsonObject.getInt("status");
                handler.obtainMessage(1,"ok").sendToTarget();
                save(status,token);
            }else {
                String mess=jsonObject.getString("message");
                Log.d("JunLog",mess);
                handler.obtainMessage(2,mess+"").sendToTarget();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*存储用户名密码，以及返回的参数*/
    private void save(int ststus,String token){
        SharedPreferences sharedPreferences=getSharedPreferences("login",0);
        sharedPreferences.edit().putString("loginname",userName_ed).commit();
        sharedPreferences.edit().putString("loginpass",passWord_ed).commit();
        sharedPreferences.edit().putInt("status",ststus).commit();
        sharedPreferences.edit().putString("object",token).commit();
    }

    /*获取用户名密码，token*/
    public String getToken(){
        SharedPreferences sharedPreferences=getSharedPreferences("login",0);
        token=sharedPreferences.getString("object","1111");
        Log.d("JunLog",token);
        username=sharedPreferences.getString("loginname","");
        password=sharedPreferences.getString("loginpass","");
        userName.setText(username);
        passWd.setText(password);
        return token;
    }

    /*进入自动登录*/
    public void oneselfLogin(){
        if (token.equals("")||username.equals("")||password.equals("")){
            return;
        }else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        getExecute();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

}
